<?php

namespace App\Http\Controllers\Admin\Customer;

use App\Http\Controllers\Controller;
use App\Http\Requests\customer\OrderRuleRequest;
use App\Models\customer\OrderRuleModel;
use App\Models\CustomerModel;
use Illuminate\Http\Request;

class OrderRule extends Controller
{
    use OrderRuleRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
//        $query = OrderRuleModel::query()->with('create_admin');
        $query = CustomerModel::with('order_rule')->where('is_big', 1);

        $items = $query->get();

        $list = $items->map(function($item) {

            $res = [
                'id' => $item->id,
                'name' => $item->name,
                'status' => $item->order_rule ? '已填写' : '未填写',
                'prefix' => $item->order_rule->prefix ?? '',
                'suffix' => $item->order_rule->suffix ?? '',
                'serial_number' => $item->order_rule->serial_number ?? '',
                'created_at' => $item->order_rule ? $item->order_rule->created_at->toDateTimeString() : '',
                'create_user' => $item->order_rule ? $item->order_rule->create_admin->staff->name: '',
            ];
            return $res;
        });

        return $this->success(['list' => $list]);
    }


    public function update(Request $request, $id){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = OrderRuleModel::where('customer_id', $id)->first();
        if (!$model) {
            $model = new OrderRuleModel();
            $model->customer_id = $id;
        }

        $model->prefix = $params['prefix'];
        $model->suffix = $params['suffix'];
        $model->serial_number = $params['serial_number'];
        $model->status = 1;
        $model->created_at = date('Y-m-d H:i:s');
        $model->created_admin_id = $auth->id;
        $model->save();

        return $this->success();
    }


}
